package com.smart.common.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ExecutorBuilder;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.smart.common.domain.BaseEntity;
import com.smart.common.enums.ConstructionStatusEnum;
import com.smart.common.enums.OpenStatusEnum;
import com.smart.common.transfer.PortTransfer;
import com.smart.common.transfer.UnitTransfer;
import com.smart.helper.CommonUtil;
import com.smart.mapper.ManageUserRegistrationMapper;
import com.smart.mapper.ProjectMapper;
import com.smart.mapper.TransferMapper;
import com.smart.model.customdo.ProjectInfoDO;
import com.smart.model.domain.*;
import com.smart.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.stream.Collectors;

/**
 * @author macbook
 */
@Slf4j
@Service
public class DataTransferService {
    @Autowired
    private ProjectOldService projectOldService;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private UnitTransfer unitTransfer;
    @Autowired
    private PortTransfer portTransfer;
    @Autowired
    private ProjectUseControlService projectUseControlService;
    @Autowired
    private TransferMapper transferMapper;
    @Autowired
    private ManageUserRegistrationService manageUserRegistrationService;
    @Autowired
    private ManageUserRegistrationMapper manageUserRegistrationMapper;
    @Autowired
    private UnitService unitService;

    private ExecutorService executorService = ExecutorBuilder.create().setCorePoolSize(100).setMaxPoolSize(200).setWorkQueue(new LinkedBlockingDeque<>(100000)).build();

    public void updateUserUnit() {
        List<ProjectDO> projectDOS = projectMapper.listAll();
        for (ProjectDO newP : projectDOS) {
            ProjectOldDO one = projectOldService.lambdaQuery().eq(ProjectOldDO::getUserName, newP.getAccount()).last("limit 1").one();
            if (one == null) {
                continue;
            }
            //最后一次台账周报人员数据
            List<ExcelDO> personList = transferMapper.queryExcelLastByOldProjectId(one.getId());
            for (ExcelDO excelDO : personList) {
                String idNumber = excelDO.getIdNumber();
                String unitName = excelDO.getUnitName();

                UnitDO newUnit = unitService.lambdaQuery().eq(UnitDO::getUnitName, unitName).eq(UnitDO::getProjectId, newP.getId()).last("limit 1").one();
                if (newUnit == null) {
                    continue;
                }

                //ManageUserRegistrationDO user = manageUserRegistrationMapper.selectByProjectIdAndIdCard(newP.getId(), idNumber);
                //if (user == null) {
                //    continue;
                //}
                //user.setUnitId(newUnit.getId());
                //manageUserRegistrationService.saveOrUpdate(user);

                List<ManageUserRegistrationDO> users = manageUserRegistrationMapper.selectByProjectIdAndIdCard2(newP.getId(), idNumber);
                if (CollectionUtils.isEmpty(users)) {
                    continue;
                }

                for (int i = 0; i < users.size(); i++) {
                    ManageUserRegistrationDO user = users.get(i);
                    if (i==0) {
                        user.setUnitId(newUnit.getId());
                        manageUserRegistrationService.saveOrUpdate(user);
                    } else {
                        manageUserRegistrationMapper.deleteById(user.getId());
                    }
                }
            }
        }

    }

    public void transfer() {
        //查询老数据
        List<ProjectOldDO> buildList = projectOldService.lambdaQuery().ne(ProjectOldDO::getState, -1).list();
        for (Pair<Long, ProjectDO> item : buildList(buildList)) {
            Long oldProjectId = item.getLeft();
            //写入项目信息
            ProjectDO projectDO = item.getRight();
            projectService.save(projectDO);

            //写入数据提报功能初始化
            projectUseControlService.save(build(projectDO));

            // 写入单位信息
            unitTransfer.transferUnit(oldProjectId, projectDO);

            //写入进出口信息
            portTransfer.portInfo(oldProjectId, projectDO);
        }
    }

    private ProjectUseControlDO build(ProjectDO projectDO) {
        ProjectUseControlDO controlDO = new ProjectUseControlDO();
        controlDO.setProjectId(projectDO.getId());
        controlDO.setManageOpenStatus(OpenStatusEnum.UN_OPEN.name());
        controlDO.setReportOpenStatus(OpenStatusEnum.UN_OPEN.name());
        controlDO.setHotWorkOpenStatus(OpenStatusEnum.UN_OPEN.name());
        return controlDO;
    }

    private List<Pair<Long, ProjectDO>> buildList(List<ProjectOldDO> oldList) {
        return oldList.stream().map(this::build).collect(Collectors.toList());
    }

    private Pair<Long, ProjectDO> build(ProjectOldDO old) {
        ProjectDO projectDO = new ProjectDO();
        projectDO.setProjectName(old.getName());
        if (!Objects.equals(old.getNumber(), "无编号")) {
            projectDO.setProjectNumber(old.getNumber());
        }
        projectDO.setEngineeringType(engineeringTypeConvert(old.getGongchengTypeId()));
        projectDO.setEngineeringCost(old.getCost());
        projectDO.setConstructionStatus(constructionStatusConvert(old.getShigongStateId()));
        projectDO.setQualityRegistrationNumber(old.getQualityNumber());
        projectDO.setLocation(old.getLocation());
        projectDO.setStartDate(old.getStartDate());
        projectDO.setFloorArea(old.getFloorage());
        projectDO.setStreetCode(old.getStreetCode());
        projectDO.setAddress(old.getAddr());
        projectDO.setShigongUnit(old.getShigongUnit());
        projectDO.setShigongHeadName(old.getShigongHeadName());
        projectDO.setShigongHeadJob(old.getShigongHeadJob());
        projectDO.setShigongHeadPhone(old.getShigongHeadPhone());
        projectDO.setShigongContactJob(old.getShigongContactJob());
        projectDO.setShigongContactName(old.getShigongContactName());
        projectDO.setShigongContactPhone(old.getShigongContactPhone());
        projectDO.setJiansheUnit(old.getJiansheUnit());
        projectDO.setJiansheHeadName(old.getJiansheHeadName());
        projectDO.setJiansheHeadPhone(old.getJiansheHeadPhone());
        projectDO.setJianliUnit(old.getJiansheUnit());
        projectDO.setJianliHeadName(old.getJianliHeadName());
        projectDO.setJianliHeadPhone(old.getJianliHeadPhone());
        projectDO.setAccount(old.getUserName());
        projectDO.setPassword(old.getPassword());
        fill(projectDO, old.getState());
        projectDO.setCreateTime(old.getAddTime());
        return Pair.of(old.getId(), projectDO);
    }

    private void fill(ProjectDO projectDO, Long state) {
        if (state == 1) {
            projectDO.setAuditType("NEW");
            projectDO.setAuditStatus("WAIT");
            projectDO.setValid(0);
        }
        if (state == -1) {
            projectDO.setAuditType("NORMAL");
            projectDO.setAuditStatus("REJECT");
            projectDO.setValid(0);
        }
        if (state == 2 || state == 5) {
            projectDO.setAuditType("NORMAL");
            projectDO.setAuditStatus("PASS");
            projectDO.setValid(1);
        }
    }

    private String engineeringTypeConvert(Long typeId) {
        if (typeId == 1) {
            return "COMMERCIAL_HOUSING";
        }
        if (typeId == 2) {
            return "AFFORDABLE_HOUSING";
        }
        if (typeId == 3) {
            return "PUBLIC_BUILDINGS";
        }
        if (typeId == 4) {
            return "INDUSTRIAL_BUILDINGS";
        }
        if (typeId == 5) {
            return "MUNICIPAL";
        }
        if (typeId == 6) {
            return "DECORATION";
        }
        if (typeId == 7) {
            return "HOUSE_ALTERATION";
        }

        return null;
    }

    private String constructionStatusConvert(Long stateId) {
        if (stateId == 1) {
            return ConstructionStatusEnum.UN_START.name();
        }
        if (stateId == 2) {
            return ConstructionStatusEnum.RUNNING.name();
        }if (stateId == 3) {
            return ConstructionStatusEnum.STOP.name();
        }if (stateId == 4) {
            return ConstructionStatusEnum.WAIT_ACCEPT.name();
        }if (stateId == 5) {
            return ConstructionStatusEnum.FINISH.name();
        }if (stateId == 6) {
            return ConstructionStatusEnum.DIE.name();
        }
        return null;
    }

    public void addressClean() {
        // 1.查询所有项目，然后查询项目
        List<ProjectInfoDO> list = projectMapper.list();
        for (ProjectInfoDO item : list) {
            //List<ManageUserRegistrationDO> registrationList = manageUserRegistrationService
            //        .lambdaQuery()
            //        .eq(ManageUserRegistrationDO::getProjectId, item.getId())
            //        .isNull(ManageUserRegistrationDO::getAddress)
            //        .list();
            List<ManageUserRegistrationDO> registrationList = manageUserRegistrationMapper.listAll(item.getId());
            for (ManageUserRegistrationDO registration : registrationList) {
                CompletableFuture.runAsync(() -> {
                ExcelDO excelDO = transferMapper.queryExcelLastByOldProjectIdAndIdCard(item.getOldId(), registration.getIdCard());
                manageUserRegistrationService.lambdaUpdate()
                        .set(ManageUserRegistrationDO::getAddress, excelDO.getAddr())
                        .eq(BaseEntity::getId, registration.getId())
                        .update();
                }, executorService);
            }
            //CompletableFuture.runAsync(() -> {
            //    List<ManageUserRegistrationDO> registrationList = manageUserRegistrationMapper.listAll(item.getId());
            //    for (ManageUserRegistrationDO registration : registrationList) {
            //        ExcelDO excelDO = transferMapper.queryExcelLastByOldProjectIdAndIdCard(item.getOldId(), registration.getIdCard());
            //        manageUserRegistrationService.lambdaUpdate()
            //                .set(ManageUserRegistrationDO::getAddress, excelDO.getAddr())
            //                .eq(BaseEntity::getId, registration.getId())
            //                .update();
            //
            //    }
            //}, executorService);

            //List<ManageUserRegistrationDO> registrationList = manageUserRegistrationMapper.listAll(item.getId());
            //for (ManageUserRegistrationDO registration : registrationList) {
            //    ExcelDO excelDO = transferMapper.queryExcelLastByOldProjectIdAndIdCard(item.getOldId(), registration.getIdCard());
            //    manageUserRegistrationService.lambdaUpdate()
            //            .set(ManageUserRegistrationDO::getAddress, excelDO.getAddr())
            //            .eq(BaseEntity::getId, registration.getId())
            //            .update();
            //
            //}

            //List<ExcelDO> personList = transferMapper.queryExcelLastByOldProjectId(item.getOldId());
            //for (ExcelDO excelDO : personList) {
            //    try {
            //        manageUserRegistrationService.lambdaUpdate()
            //                .set(ManageUserRegistrationDO::getAddress, excelDO.getAddr())
            //                .eq(ManageUserRegistrationDO::getProjectId, item.getId())
            //                .eq(ManageUserRegistrationDO::getIdCard, excelDO.getIdNumber())
            //                .update();
            //    } catch (Exception ex) {
            //        ex.printStackTrace();
            //        log.error("----> excelDO={}", JSON.toJSONString(excelDO));
            //    }
            //}
        }
    }
}
